<template>
  <div class="account-manage">
    <el-card class="account-card">
      <template #header>
        <div class="card-header">
          <span>账号管理</span>
        </div>
      </template>
      
      <el-form 
        :model="userForm" 
        :rules="userRules" 
        ref="userFormRef" 
        label-width="100px"
        class="user-form">
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <p class="tips">点击上传头像，JPG/PNG格式，不超过2MB</p>
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        
        <el-divider>安全设置</el-divider>
        
        <el-form-item label="修改密码">
          <el-button type="primary" @click="showPasswordDialog">修改密码</el-button>
        </el-form-item>
        
        <el-form-item label="绑定手机">
          <div class="bind-phone">
            <span>{{ userForm.phone ? '已绑定手机：' + userForm.phone : '未绑定手机' }}</span>
            <el-button type="primary" plain size="small" @click="showBindPhoneDialog">
              {{ userForm.phone ? '更换手机' : '绑定手机' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="账号安全">
          <el-switch
            v-model="userForm.enableTwoFactor"
            active-text="开启双因素认证"
            inactive-text="关闭双因素认证"
            @change="handleTwoFactorChange">
          </el-switch>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialogVisible"
      width="500px">
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.oldPassword" 
            show-password
            placeholder="请输入原密码">
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.newPassword" 
            show-password
            placeholder="请输入新密码">
          </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.confirmPassword" 
            show-password
            placeholder="请再次输入新密码">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 绑定手机对话框 -->
    <el-dialog
      title="绑定手机"
      v-model="phoneDialogVisible"
      width="500px">
      <el-form
        :model="phoneForm"
        :rules="phoneRules"
        ref="phoneFormRef"
        label-width="100px">
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="phoneForm.phone" 
            placeholder="请输入手机号码">
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="captcha-container">
            <el-input 
              v-model="phoneForm.code" 
              placeholder="请输入验证码">
            </el-input>
            <el-button 
              :disabled="captchaDisabled" 
              @click="sendCaptcha">
              {{ captchaText }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindPhone">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'AccountManage',
  components: {
    Plus
  },
  setup() {
    // 表单引用
    const userFormRef = ref(null)
    const passwordFormRef = ref(null)
    const phoneFormRef = ref(null)
    
    // 用户表单数据
    const userForm = reactive({
      username: '',
      realName: '',
      phone: '',
      email: '',
      avatar: '',
      enableTwoFactor: false
    })
    
    // 用户表单验证规则
    const userRules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }
    
    // 密码对话框可见性
    const passwordDialogVisible = ref(false)
    
    // 密码表单数据
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 验证新密码与确认密码是否一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    // 密码表单验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不少于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    }
    
    // 手机对话框可见性
    const phoneDialogVisible = ref(false)
    
    // 手机表单数据
    const phoneForm = reactive({
      phone: '',
      code: ''
    })
    
    // 手机表单验证规则
    const phoneRules = {
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码为6位数字', trigger: 'blur' }
      ]
    }
    
    // 验证码按钮状态
    const captchaDisabled = ref(false)
    const captchaText = ref('获取验证码')
    let captchaTimer = null
    
    // 初始化用户数据
    onMounted(() => {
      // 这里应该调用API获取用户信息
      // 模拟获取数据
      setTimeout(() => {
        userForm.username = localStorage.getItem('username') || '用户'
        userForm.realName = '张三'
        userForm.phone = '13800138000'
        userForm.email = 'zhangsan@example.com'
        userForm.avatar = localStorage.getItem('userAvatar') || ''
        userForm.enableTwoFactor = false
      }, 500)
    })
    
    // 头像上传处理
    const handleAvatarChange = (file) => {
      // 这里应该调用API上传图片
      // 模拟上传
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        userForm.avatar = reader.result
      }
    }
    
    // 显示修改密码对话框
    const showPasswordDialog = () => {
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      passwordDialogVisible.value = true
    }
    
    // 更新密码
    const updatePassword = async () => {
      const valid = await passwordFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      // 这里应该调用API更新密码
      // 模拟更新
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
    }
    
    // 显示绑定手机对话框
    const showBindPhoneDialog = () => {
      phoneForm.phone = userForm.phone
      phoneForm.code = ''
      phoneDialogVisible.value = true
    }
    
    // 发送验证码
    const sendCaptcha = () => {
      if (!phoneForm.phone) {
        ElMessage.warning('请先输入手机号码')
        return
      }
      
      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
        ElMessage.warning('请输入正确的手机号码')
        return
      }
      
      // 这里应该调用API发送验证码
      // 模拟发送
      ElMessage.success('验证码已发送')
      
      // 倒计时
      captchaDisabled.value = true
      let countdown = 60
      captchaText.value = `${countdown}秒后重新获取`
      
      captchaTimer = setInterval(() => {
        countdown--
        captchaText.value = `${countdown}秒后重新获取`
        if (countdown <= 0) {
          clearInterval(captchaTimer)
          captchaDisabled.value = false
          captchaText.value = '获取验证码'
        }
      }, 1000)
    }
    
    // 绑定手机
    const bindPhone = async () => {
      const valid = await phoneFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      // 这里应该调用API绑定手机
      // 模拟绑定
      userForm.phone = phoneForm.phone
      ElMessage.success('手机绑定成功')
      phoneDialogVisible.value = false
    }
    
    // 处理双因素认证变更
    const handleTwoFactorChange = (value) => {
      // 这里应该调用API更新双因素认证设置
      // 模拟更新
      ElMessage.success(`已${value ? '开启' : '关闭'}双因素认证`)
    }
    
    // 提交表单
    const submitForm = async () => {
      const valid = await userFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      // 这里应该调用API更新用户信息
      // 模拟更新
      ElMessage.success('用户信息更新成功')
      
      // 更新本地存储
      localStorage.setItem('userAvatar', userForm.avatar)
    }
    
    // 重置表单
    const resetForm = () => {
      userFormRef.value.resetFields()
    }
    
    return {
      userFormRef,
      userForm,
      userRules,
      passwordDialogVisible,
      passwordFormRef,
      passwordForm,
      passwordRules,
      phoneDialogVisible,
      phoneFormRef,
      phoneForm,
      phoneRules,
      captchaDisabled,
      captchaText,
      handleAvatarChange,
      showPasswordDialog,
      updatePassword,
      showBindPhoneDialog,
      sendCaptcha,
      bindPhone,
      handleTwoFactorChange,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.account-manage {
  padding: 10px;
}

.account-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.bind-phone {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.captcha-container {
  display: flex;
}

.captcha-container .el-input {
  margin-right: 10px;
}

.el-divider {
  margin: 30px 0;
}
</style> 